import xlrd
import xlwt
from os.path import exists
from os import mkdir
from xlutils.copy import copy


# 开局检测有没有，有的话直接使用，没有的话就创建
# 使用绝对路径，将其放在D盘的send_to_song,文件夹下
def check_file(tsp, path_dir="D:\\send_to_song\\"):
    if exists(path_dir):
        if exists('{}send_to_song_{}.xlsx'.format(path_dir, tsp)):
            pass
        else:
            workbook = xlwt.Workbook(encoding='utf-8')
            workbook.add_sheet('send_to_song')  # 添加一个空表
            workbook.save('{}send_to_song_{}.xlsx'.format(path_dir, tsp))
    else:
        # 创建文件夹
        mkdir('D:\\send_to_song')
        workbook = xlwt.Workbook(encoding='utf-8')
        workbook.add_sheet('send_to_song')  # 添加一个空表
        workbook.save('{}send_to_song.xlsx_{}'.format(path_dir, tsp))
    return True


def write_excel_xlsx(path_xlsx, union_dict_: dict, sheet_name='send_to_song'):
    data = xlrd.open_workbook(path_xlsx)
    excel = copy(wb=data)  # 完成xlrd对象向xlwt对象转换
    excel_table = excel.get_sheet(0)  # 获得要操作的页
    table = data.sheets()[0]
    n_rows = table.nrows  # 获得行数
    for question, answer in union_dict_.items():
        excel_table.write(n_rows, 0, question)  # 先行后列
        excel_table.write(n_rows, 1, answer)
        n_rows = n_rows + 1
    excel.save(path_xlsx)
    # print("xlsx格式表格写入数据成功！")
    return True
